<?php

class AuthController extends Core_Controller_Action_Ajax {
	public function loginAction() {
		$translationHelper = $this->view->getHelper ( 'T' );
		if (! Zend_Validate::is ( $login = $this->getRequest ()->getParam ( 'username' ), 'Regex', array ('/^([a-zA-Z0-9_]){5,18}$/' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ðµ Ñ–Ð¼â€™Ñ� Ñ‡Ð¸ Ð¿Ð°Ñ€Ð¾Ð»ÑŒ' );
		
		if (! Zend_Validate::is ( $password = $this->getRequest ()->getParam ( 'password' ), 'Regex', array ('/^([a-zA-Z0-9_]){5,18}$/' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ðµ Ñ–Ð¼â€™Ñ� Ñ‡Ð¸ Ð¿Ð°Ñ€Ð¾Ð»ÑŒ' );
		
		$login = strtolower ( $login );
		
		$adapter = Zend_Registry::get ( 'Zend_Auth' )->setIdentity ( $login )->setCredential ( $password );
		
		$result = Zend_Auth::getInstance ()->authenticate ( $adapter );
		
		if ($result->isValid ()) {
			Zend_Auth::getInstance ()->getStorage ()->write ( $user_data = $adapter->getResultRowObject ( array ('login', 'price_scheme', 'is_admin' ) ) );
			
			$this->push ( 'login', $user_data->login );
		} else
			$this->error ( $translationHelper->t ( 'pop-up Incorrect username or password' ) );
	}
	
	public function callAction()
	{	
		$translationHelper = $this->view->getHelper('T');
		$result = array();
		
		$number = $this->getRequest()->getParam('number');
		$name = $this->getRequest()->getParam('name');
		$desc = $this->getRequest()->getParam('desc');

		if(!Zend_Validate::is($number, 'Regex',	array('/^([+()0-9_]){3,18}$/'))) {
			$result['status'] = false;	
			$this->error('Невірний номер');
		}
				
	   	if (isset($number) && isset($name) && (trim($number)!='') && (trim($name)!='') && (strlen($number)>=5)) {
    			$result['status'] = true;
    			$result['name'] = $name;
    			$this->push('call', $result); 
    			
    			$this->view->number = $number;
    			$this->view->name = $name;
    			$this->view->desc = $desc;
    			
    			$bodyHtml = $this->view->renderControl('contactMail');
    			$setSubject = $translationHelper->t("Call to ".$name);   		
//    			$this->Maildd($name, $bodyHtml, $setSubject);
    	} else {
    		$result['status'] = false;
    		if (trim($number)=='') {
    			$this->error("Номер не може бути пустим");
    		}
    		if (trim($name)=='') {
    			$this->error("Ім'я не може бути пустим");
    		}
    	}
	}	
	
	private function Mail($userEmail, $bodyHtml, $setSubject) {
		$mail = new Zend_Mail('UTF-8', Zend_Mime::ENCODING_8BIT);
        $mail->setBodyHtml($bodyHtml);
     	$mail->setFrom('Zala');
     	$mail->addTo($userEmail);
     	$mail->setSubject($setSubject);
     	$mail->send();
	}

	private function Maildd($userName, $bodyHtml, $setSubject) {
		$mail = new Zend_Mail('UTF-8', Zend_Mime::ENCODING_8BIT);
     	$mail->setBodyHtml($bodyHtml);
     	$mail->setFrom($userName);
     	$mail->addTo("firmanigorromanovuch@gmail.com");
     	$mail->setSubject($setSubject);
     	$mail->send();
	}	
	
	public function saveAction() {
		if (! Zend_Validate::is ( $login = $this->getRequest ()->getParam ( 'username' ), 'Regex', array ('|([a-z0-9_\.\-]{1,20})@([a-z0-9\.\-]{1,20})\.([a-z]{2,4})|is' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ð¸Ð¹ email' );
		
		if (! Zend_Validate::is ( $password = $this->getRequest ()->getParam ( 'password' ), 'Regex', array ('/^([a-zA-Z0-9_]){5,18}$/' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ð¸Ð¹ Ð¿Ð°Ñ€Ð¾Ð»ÑŒ' );
			
		$api = Zend_Registry::get ( 'api' );
		$username = $this->getRequest ()->getParam ( 'username' );
		$password = $this->getRequest ()->getParam ( 'password' );
		if (!$api->User->searchUser($username))
			$api->User->create_new_user($username, $password);
		else 
			$this->error ( 'Ð¢Ð°ÐºÐ¸Ð¹ email Ð²Ð¶Ðµ Ñ–Ñ�Ð½ÑƒÑ”!' );
	}
	
	public function chengepassAction() {
		if (! Zend_Validate::is ( $login = $this->getRequest ()->getParam ( 'username' ), 'Regex', array ('|([a-z0-9_\.\-]{1,20})@([a-z0-9\.\-]{1,20})\.([a-z]{2,4})|is' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ð¸Ð¹ email' );
		
		if (! Zend_Validate::is ( $password = $this->getRequest ()->getParam ( 'password' ), 'Regex', array ('/^([a-zA-Z0-9_]){5,18}$/' ) ))
			$this->error ( 'Ð�ÐµÐ²Ñ–Ñ€Ð½Ð¸Ð¹ Ð¿Ð°Ñ€Ð¾Ð»ÑŒ' );	
			
		$api = Zend_Registry::get ( 'api' );

		if (!$api->User->searchUser($login))
			$this->error ( 'Ð¢Ð°ÐºÐ¾Ð³Ð¾ ÐºÐ¾Ñ€Ð¸Ñ�Ñ‚ÑƒÐ²Ð°Ñ‡Ð° Ð½Ðµ Ñ–Ñ�Ð½ÑƒÑ”!' );
		else {
			$api->User->chengepass($login, $password);
			$login = strtolower ( $login );
			$adapter = Zend_Registry::get ( 'Zend_Auth' )->setIdentity ( $login )->setCredential ( $password );
			Zend_Auth::getInstance ()->getStorage ()->write ( $user_data = $adapter->getResultRowObject ( array ('login', 'price_scheme', 'is_admin' ) ) );
			
			$this->push ( 'login', $login );
		}
	}
	
	public function logoutAction() {
		Zend_Auth::getInstance ()->clearIdentity ();
		$api = Zend_Registry::get ( 'api' );
		$api->Cart->clear ();
		$this->_redirect ( $this->view->url ( array (), null, true ) );
	}
	
	public function addtocartAction() {
		$id = ( int ) $this->getRequest ()->getParam ( 'id' );
		$api = Zend_Registry::get ( 'api' );
		$api->Cart->setProduct ( $id, 1 );
		$this->view->amount = $api->Cart->getAmount ();
		$this->push ( 'cartHtml', $this->view->renderControl ( 'displayCart' ) );
	}
	
	public function delproductAction() {
		//		if(Zend_Registry::get('Core_User')->isGuest())
		//			throw new Exception('You need to be a user to add buy product.');
		

		$id = ( int ) $this->getRequest ()->getParam ( 'id' );
		$api = Zend_Registry::get ( 'api' );
		$api->Cart->setProduct ( $id, 0 );
		$this->push ( 'id', $id );
		$this->view->amount = $api->Cart->getAmount ();
		$this->push ( 'cartHtml', $this->view->renderControl ( 'displayCart' ) );
		$this->push ( 'redirect', $this->view->amount == 0 );
		$this->push ( 'total', $this->view->price ( $api->Cart->getAccount () ) );
	}
	
	public function saveproductAction() {
		$data = $this->getRequest ()->getParam ( 'data' );
		$api = Zend_Registry::get ( 'api' );
		$api->Cart->setProducts ( $data );
		$this->view->amount = $api->Cart->getAmount ();
		$this->push ( 'cartHtml', $this->view->renderControl ( 'displayCart' ) );
		$this->push ( 'total', $this->view->price ( $api->Cart->getAccount () ) );
	}
	
	protected function _syncCategory(Zend_Db_Adapter_Abstract $adapter) {
		$adapter->query ( 'DROP TABLE IF EXISTS `categories`;' );
		$adapter->query ( "CREATE TABLE `categories` (
			  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `descript` text COLLATE utf8_unicode_ci,
			  `img_src` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
			  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
			  PRIMARY KEY (`id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;" );
		$adapter->query ( 'LOCK TABLES `categories` WRITE;' );
		
		$res = simplexml_load_file ( APPLICATION_PATH . '/../data/categories.xml' );
		$sql_script = "INSERT INTO `categories` VALUES ";
		$s = true;
		foreach ( $res as $col ) {
			if ($s === true) {
				$s = false;
			} else
				$sql_script .= ',';
			$sql_script .= '(' . implode ( ',', array ('id' => ( int ) $col->id, 'title' => "'" . mysql_real_escape_string ( ( string ) $col->title ) . "'", 'description' => (is_null ( $col->description ) || ($col->description == '')) ? 'NULL' : "'" . mysql_real_escape_string ( ( string ) $col->description ) . "'", 'img_src' => 'NULL', 'parent_id' => ( int ) $col->parent_id ) ) . ')';
		}
		trim ( $sql_script, ',' );
		$sql_script .= ';';
		
		$adapter->query ( $sql_script );
		$adapter->query ( 'UNLOCK TABLES;' );
	}
	
	protected function _syncProduct(Zend_Db_Adapter_Abstract $adapter) {
		$xml = new XMLReader ();
		$xml->open ( APPLICATION_PATH . '/../data/products.xml', 'cp1251' );
		$xml->read ();
		var_dump ( $xml );
	
	}
	
	public function syncAction() {
		
		$adapter = Zend_Db_Table::getDefaultAdapter ();
		$this->_syncProduct ( $adapter );
	}
}